from django.shortcuts import render
from course.models import Video
from users.models import GradeStudent
from .serializer import GoodsImageSerializer,CourseSummarySerializer,CourseDetailSerializer
from .serializer import CourseAuthDetailSerializer,CourseClassAuthDetailSerializer
from rest_framework.authentication import SessionAuthentication
from .models import CourseBanner,Course
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated,IsAdminUser
from .models import HotSearchWords
from .serializer import HotWordsSerializer,VideoDetailSerializer,CourseCreateSerializer
from rest_framework import status
from utils.permission import IsTeacher
from rest_framework_extensions.cache.mixins import CacheResponseMixin


def authenticate(request):
    return request.user and request.user.is_authenticated


class CoursePagination(LimitOffsetPagination):
    limit_query_param = 'limit'
    limit_query_description = ('限定请求的课程数')
    default_limit = 5


class CourseSearchFilter(filters.SearchFilter):
    def get_search_terms(self, request):
        """
        Search terms are set by a ?search=... query parameter,
        and may be comma and/or whitespace delimited.
        """
        params = request.query_params.get(self.search_param, '')

        return params.replace(',', ' ').split()


class BannerViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    """
    list:
    获取轮播图列表
    """
    queryset = CourseBanner.objects.all()
    serializer_class = GoodsImageSerializer


class CourseViewSet(mixins.UpdateModelMixin,mixins.CreateModelMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    list:
    获取课程摘要信息的列表

    retrieve:
    获取课程的详情页信息 如果登陆包含视频信息，否则只有课程信息
    create:
    创建课程

    Update:
    更新课程
    """

    queryset = Course.objects.all().order_by("-click_nums")
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name', 'desc','grade__GradeName')
    pagination_class = CoursePagination
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)

    def get_permissions(self):
        if self.action == "create":
            return [IsAuthenticated(),IsTeacher()]
        else :
            return []

    def get_serializer_class(self):
        if self.action == "list":
            return CourseSummarySerializer
        if self.action == "retrieve":
            if authenticate(self.request):
                if GradeStudent.objects.filter(grade=self.get_object().grade,user=self.request.user)\
                        or self.get_object().grade.teacher == self.request.user \
                        or self.get_object().teacher == self.request.user:
                    return CourseClassAuthDetailSerializer
                else:
                    return CourseAuthDetailSerializer
        return CourseCreateSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_nums += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class HotSearchsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    list:
    获取热搜词列表
    """
    queryset = HotSearchWords.objects.all()
    serializer_class = HotWordsSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        result = [i.get("keywords")for i in serializer.data]
        return Response(result)


class VideoViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet):

    """
    retrieve:
    获取视频详情页
    list:
    获取视频列表(目前普通用户暂不支持返回全部内容)
    """
    queryset = Video.objects.all()
    serializer_class = VideoDetailSerializer
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if GradeStudent.objects.filter(grade=instance.lesson.course.grade,user=request.user):
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
        else :
            return Response({"detail":"用户并没有加入该班级"},status=status.HTTP_404_NOT_FOUND)

    def list(self, request, *args, **kwargs):
        if request.user.is_staff:
            queryset = self.filter_queryset(self.get_queryset())

            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)

            serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)
        return Response({"detail":"暂不支持查看全部内容"},status=status.HTTP_404_NOT_FOUND)



